<template>
  <div class="flex flex-col h-full " @keydown.ctrl.s.prevent="handleSave">
    <div class="h-10 flex items-center border-b justify-between px-2">
      <div class="flex space-x-1 items-center flex-1">
        <n-button-group>
          <n-button size="small" @click="handleBack">
            <TextIcon tip="返回" icon="ri:arrow-left-s-line"></TextIcon>
          </n-button>
          <n-button size="small" @click="handleNew">
            <TextIcon tip="新建" icon="mdi:add"></TextIcon>
          </n-button>
          <PostEditDrawer v-model:is-show="postEditDrawerShow">
            <div class="border-b p-2">
              <h3>更多设置</h3>
            </div>
            <div class="flex space-x-3 container mx-auto mt-3 px-1">
              <div class="hidden md:block md:mt-5 w-40">
                <ImageUpload v-model:image="post.cover" placeholder="封面上传"></ImageUpload>
              </div>
              <div class="space-y-3 flex flex-col flex-1">
                <div class="block md:hidden max-h-32">
                  <ImageUpload v-model:image="post.cover" placeholder="封面上传"></ImageUpload>
                </div>
                <n-input v-model:value="post.title"
                         show-count maxlength="40" size="large" placeholder="标题"></n-input>
                <div class=" flex items-center space-x-3">
                  <VisibilitySwitch style="width: 80px" size="large"
                                    v-model:visibility="post.visibility"></VisibilitySwitch>
                  <CategorySelect size="large" v-model:category="post.category"></CategorySelect>
                </div>
                <TagSelect size="large" :max-tag-count="5" v-model:tags="post.tags"></TagSelect>
              </div>
            </div>
          </PostEditDrawer>
        </n-button-group>
        <div class="hidden lg:flex lg:items-center space-x-1">
          <n-input style="min-width: 90px;max-width: 180px" show-count
                   v-model:value="post.title"
                   maxlength="40" autosize size="small" placeholder="标题"></n-input>
          <CategorySelect style="width: 90px" v-model:category="post.category"></CategorySelect>
          <TagSelect :max-tag-count="1" style="width: 180px" v-model:tags="post.tags"></TagSelect>
          <VisibilitySwitch style="width: 80px" size="large" v-model:visibility="post.visibility"></VisibilitySwitch>
          <ImageUploadBar placeholder="封面上传" v-model:image="post.cover"></ImageUploadBar>
        </div>
        <div class="truncate text-xs text-gray-400">
          <div v-if="isSaveLoading">
            <TextIcon :size="14" text="正在保存..." icon="line-md:loading-twotone-loop"></TextIcon>
          </div>
          <div v-else>
            {{ saveTime ? '最近一次更新 ' + dayjs(saveTime).format('HH:mm:ss') : '' }}
          </div>
        </div>
      </div>
      <div class="flex items-center space-x-3">
        <AiButton :size="19"></AiButton>
        <BoardButton :size="19"></BoardButton>
        <ThemeSwitch :size="25"></ThemeSwitch>
        <n-button-group>
          <n-button type="info" secondary size="small" @click="handlePreview">预览</n-button>
          <n-button v-if="mode==='create'" type="success" secondary size="small" @click="handleCreate">提交</n-button>
          <n-button v-else-if="mode==='edit'" type="success" secondary size="small" @click="handleSave">保存</n-button>
        </n-button-group>
      </div>
    </div>
    <div class="flex-1 overflow-hidden">
      <n-scrollbar>
        <FullLoading :loading="!isRenderFinish"></FullLoading>
        <EditMarkdown v-model:content="post.content" @renderFinish="isRenderFinish=true"></EditMarkdown>
      </n-scrollbar>
    </div>
  </div>
  <PostPreviewModal ref="previewRef"></PostPreviewModal>
</template>

<script setup lang="ts">

import TextIcon from "@/components/pc/icon/TextIcon.vue";
import CategorySelect from "@/components/pc/select/CategorySelect.vue";
import TagSelect from "@/components/pc/select/TagSelect.vue";
import {onMounted, ref, watch} from "vue";
import {useRoute} from "vue-router";
import api from "@/api";
import PostEditDrawer from "@/components/pc/drawer/PostEditDrawer.vue";
import ImageUpload from "@/components/pc/image/ImageUpload.vue";
import ImageUploadBar from "@/components/pc/image/ImageUploadBar.vue";
import VisibilitySwitch from "@/components/pc/switch/VisibilitySwitch.vue";
import router from "@/router";
import PostPreviewModal from "@/components/pc/modal/PostPreviewModal.vue";
import EditMarkdown from "@/components/common/markdown/EditMarkdown.vue";
import ThemeSwitch from "@/components/pc/switch/ThemeSwitch.vue";
import FullLoading from "@/components/pc/animation/FullLoading.vue";
import {useDebounceFn, useTitle} from '@vueuse/core'
import {storeToRefs} from "pinia";
import {useAdminStore} from "@/store/module/admin";
import {useUserStore} from "@/store/module/user";
import dayjs from "@/utils/dayjs";
import AiButton from "@/components/pc/button/AiButton.vue";
import BoardButton from "@/components/pc/button/boardButton.vue";

const adminStore = useAdminStore()
const {userInfo} = storeToRefs(useUserStore())
const title = useTitle()
const previewRef = ref()
const postEditDrawerShow = ref(false)
const post = ref<IPost>({
  id: '',
  title: '',
  username: '',
  content: '',
  cover: '',
  tags: [],
  visibility: 'private',
  category: {
    name: '',
    id: null,
  }
})
const id = ref('')
const route = useRoute()
const isRenderFinish = ref(false)
const mode = ref('edit')
const isSaveLoading = ref(false)
const saveTime = ref('')

onMounted(() => {
  if (route.query.id) {
    id.value = route.query.id as string
    getPost()
  } else {
    mode.value = 'create'
    title.value = '新建文章'
  }
})

const getPost = () => {
  window.$loadingBar.start()
  api.post.id({
    id: id.value,
  }).then((res: any) => {
    if (res.data.code === 0) {
      post.value = res.data.data as IPost
      post.value.tags = res.data.data.tags ? JSON.parse(res.data.data.tags) : []
      post.value.category = {
        name: post.value.categoryName,
        id: post.value.categoryId
      }
      adminStore.openPost(post.value, '编辑')
    }
  }).finally(() => {
    window.$loadingBar.finish()
  })
}

watch(() => post.value, (value, oldValue) => {
  title.value = post.value.title
  if (oldValue?.title !== '' && value.id && value.title && value.cover && value.content && value.category.id) {
    autoSave()
  }
}, {
  deep: true,
  immediate: true
})

const handleNew = () => {
  let r = router.resolve({
    path: '/pc/manage/edit',
  })
  window.open(r.href, '_blank');
}
const handleBack = () => {
  router.push({
    path: '/pc/manage'
  })
}
const handleCreate = () => {
  let form = JSON.parse(JSON.stringify(post.value))
  form.tags = JSON.stringify(form.tags)
  form.username = userInfo.value.username
  form.userId = userInfo.value.id
  form.categoryId = post.value.category.id
  form.categoryName = post.value.category.name
  api.post.create(form).then((res: any) => {
    if (res.data.code === 0) {
      window.$message.success('创建成功')
      mode.value = 'edit'
      router.push({
        path: '/pc/manage/edit',
        query: {
          id: res.data.data.id
        }
      })
      id.value = res.data.data.id
      post.value.id = res.data.data.id
      adminStore.openPost(post.value, '新建')
    }
  })
}
const handleSave = () => {
  let form = JSON.parse(JSON.stringify(post.value))
  form.tags = JSON.stringify(form.tags)
  form.username = userInfo.value.username
  form.userId = userInfo.value.id
  form.categoryId = post.value.category.id
  form.categoryName = post.value.category.name
  isSaveLoading.value = true
  api.post.update(form).then((res: any) => {
    if (res.data.code === 0) {
      saveTime.value = new Date().toLocaleString()
      adminStore.openPost(post.value, '编辑')
    }
  }).finally(() => {
    isSaveLoading.value = false
  })
}

const autoSave =useDebounceFn(handleSave, 5000)

const handlePreview = () => {
  previewRef.value.doParamsShow({
    post: post.value
  })
}

</script>

<style scoped>

</style>